<template>
	<div class="fault-dialog-content">
		<el-tabs v-model="activeTab">
			<el-tab-pane v-if="showFirst" label="一次故障" name="first">
				<div class="fault-content">
					<el-form label-width="80px">

						<!-- 故障相位 -->
						<el-form-item label="故障相位">
							<el-checkbox-group v-model="faultXiangWei" @change="updateData(tableDataCopy,tableData,faultXiangWei,faultFeature,distance)" >
								<el-checkbox label="A">A相</el-checkbox>
								<el-checkbox label="B">B相</el-checkbox>
								<el-checkbox label="C">C相</el-checkbox>
								<el-checkbox label="接地">接地</el-checkbox>
								<el-checkbox label="短路">短路</el-checkbox>
							</el-checkbox-group>
						</el-form-item>

						<!-- 故障特性 -->
						<el-form-item label="故障类型" v-if="localType=='xianlu'">
							<el-radio-group v-model="faultFeature"  @change="updateData(tableDataCopy,tableData,faultXiangWei,faultFeature,distance)">
								<el-radio label="">全部</el-radio>
								<el-radio label="瞬时">瞬时</el-radio>
								<el-radio label="永久">永久</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="故障类型" v-if="localType=='bianyaqi'">
							<el-radio-group v-model="faultFeature"  @change="updateData(tableDataCopy,tableData,faultXiangWei,faultFeature,distance)">
								<el-radio label="">全部</el-radio>
								<el-radio label="高压侧">高压侧</el-radio>
								<el-radio label="中压侧">中压侧</el-radio>
								<el-radio label="低压侧">低压侧</el-radio>
								<el-radio label="内部故障">内部故障</el-radio>
								<el-radio label="非电量">非电量</el-radio>
							</el-radio-group>
						</el-form-item>
						<!-- 故障位置 -->
						<el-form-item label="故障位置" v-if="localType==='xianlu'">
							<el-radio-group v-model="distance"  @change="updateData(tableDataCopy,tableData,faultXiangWei,faultFeature,distance)">
								<el-radio label="">全部</el-radio>
								<el-radio label="以外">距首端70%以外</el-radio>
								<el-radio label="以内">距首端70%以内</el-radio>
							</el-radio-group>
						</el-form-item>
					<div class="txts">
						<div style="display: flex">
							<div style="width: 10%;text-align: center;border-right: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 5px 0">选中</div>
							<div style="width: 90%;text-align: center;border-bottom: 1px solid #ccc;padding: 5px 0">内容</div>
						</div>
						<div v-if="tableDataCopy.length!==0">
						<div  v-for="(item,index) in tableDataCopy" :key="index" style="display: flex;"     class="table-row"
								 :class="{ selected: selectedID.includes(item.cl_index) } "  @click="selectRow(item.cl_index,selectedID,1)">
							<div style="width: 10%;text-align: center;border-right: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 5px 0;display: flex;justify-content: center;align-items: center">
								<div style="border: 1px solid gray; width: 1rem; height: 1rem; display: flex; align-items: center; justify-content: center; font-size: 0.8rem;" v-if="selectedID.includes(item.cl_index)">
									✔
								</div>

								<div style="border: 1px solid gray;width:1rem;height: 1rem" v-else></div>
							</div>
							<div style="width: 90%;border-bottom: 1px solid #ccc;padding: 5px 5px;box-sizing: border-box;white-space: nowrap;overflow-x: auto">{{item.name}}</div>
						</div>
					</div>
						<div v-else style="display: flex;justify-content: center;align-items: center;height: 80%">暂无数据</div>
					</div>
					</el-form>
				</div>
			</el-tab-pane>

			<el-tab-pane  label="二次故障" name="second" v-if="this.localType!=='muxian'">
				<div class="fault-content">
					<el-form label-width="80px">

						<div class="txts">
							<div style="display: flex">
								<div style="width: 10%;text-align: center;border-right: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 5px 0">选中</div>
								<div style="width: 90%;text-align: center;border-bottom: 1px solid #ccc;padding: 5px 0">内容</div>
							</div>
							<div v-if="tableDataCopy_2.length!==0">
							<div v-for="(item,index) in tableDataCopy_2" :key="index" style="display: flex;"     class="table-row"
									 :class="{ selected: selectedID_2.includes(item.cl_index) } "  @click="selectRow(item.cl_index,selectedID_2,2)">
								<div style="width: 10%;text-align: center;border-right: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 5px 0;display: flex;justify-content: center;align-items: center">
									<div style="border: 1px solid gray; width: 1rem; height: 1rem; display: flex; align-items: center; justify-content: center; font-size: 0.8rem;" v-if="selectedID_2.includes(item.cl_index)">
										✔
									</div>
									<div style="border: 1px solid gray;width:1rem;height: 1rem" v-else></div>
								</div>
								<div style="width: 90%;border-bottom: 1px solid #ccc;padding: 5px 5px;box-sizing: border-box;white-space: nowrap;overflow-x: auto">{{item.name}}</div>
							</div>
							</div>
								<div v-else style="display: flex;justify-content: center;align-items: center;height: 80%">暂无数据</div>
						</div>
					</el-form>
				</div>
			</el-tab-pane>

			<el-tab-pane  label="异常" name="third">
				<div class="fault-content">

					<div class="txts">
						<div style="display: flex">
							<div style="width: 10%;text-align: center;border-right: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 5px 0">选中</div>
							<div style="width: 90%;text-align: center;border-bottom: 1px solid #ccc;padding: 5px 0">内容</div>
						</div>
						<div v-if="tableDataCopy_3.length!==0">
						<div v-for="(item,index) in tableDataCopy_3" :key="index" style="display: flex;"     class="table-row"
								 :class="{ selected: selectedID_3[index]?.id === item.cl_index } "  @click="selectRow(item.cl_index,selectedID_3,3,index)">
							<div style="width: 10%;text-align: center;border-right: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 5px 0;display: flex;justify-content: center;align-items: center">
								<div style="border: 1px solid gray; width: 1rem; height: 1rem; display: flex; align-items: center; justify-content: center; font-size: 0.8rem;" v-if="selectedID_3[index]?.id === item.cl_index">
									✔
								</div>
								<div style="border: 1px solid gray;width:1rem;height: 1rem" v-else></div>
							</div>
							<div style="width: 90%;border-bottom: 1px solid #ccc;padding: 5px 5px;box-sizing: border-box;display: flex;justify-content: space-between">
								<div
										style="width: 70%; white-space: nowrap; overflow-x: auto; height: 100%; display: flex; align-items: center;border: 1px solid transparent">
									{{ item.name }}
								</div>
								<div v-if="selectedID_3[index]?.id === item.cl_index">
									<el-select size="mini" v-model="selectedID_3[index].val" @change="saveName(selectedID_3[index].val,index,item.ex_val)">
										<el-option v-for="(items,index) in item.ex_val" :key="index" :label="items.name" :value="items.val">{{items.name}}</el-option>
									</el-select>
								</div>
							</div>
						</div>
						</div>
						<div v-else style="display: flex;justify-content: center;align-items: center;height: 80%">暂无数据</div>
					</div>
				</div>
			</el-tab-pane>
		</el-tabs>

		<!-- 加入教案 -->
		<el-collapse>
			<el-collapse-item title="加入教案">
				<el-form label-width="80px">
					<el-form-item label="时间间隔">
						<el-input-number
								v-model="timeInterval"
								:min="0"
								controls-position="right"
						></el-input-number>
						<span class="ms-label">ms</span>
					</el-form-item>

					<el-form-item label="选择教案">
						<el-select v-model="selectedPlan" style="width: 150px" >
							<el-option v-for="(item,index) in jiaoAnList" :key="index" :label="item.name" :value="item.id"></el-option>
						</el-select>
						<el-button size="medium" type="primary" style="margin-left: 10px" @click="addEvent">
							加入教案
						</el-button>
					</el-form-item>
				</el-form>
			</el-collapse-item>
		</el-collapse>


	</div>
</template>

<script>
import {addJaEvent, getJAn} from "@/api/api";


export default {
	name: 'FaultDialog',
	data() {
		return {
			activeTab: 'first',
			selectedID:[],
			selectedID_2:[],
			selectedID_3:[],
			faultXiangWei: [],
			faultFeature: '',
			distance: '',
			faultXiangWei_2: [],
			faultFeature_2: '',
			distance_2: '',
			faultXiangWei_3: [],
			faultFeature_3: '',
			distance_3: '',
			timeInterval: 0,
			selectedPlan: '',
			ws:this.$store.state.webSocket,
			jiaoAnList:[],
			tableData: [

			],
			tableDataCopy:[],
			selectedRowIndex: null,
			tableData_2: [],
			tableDataCopy_2:[],
			selectedRowIndex_2: null,
			tableData_3: [],
			tableDataCopy_3:[],
			selectedRowIndex_3: null,
			// rangeOptions:[	{label:'一次故障',value:'一次故障'},
			// 	{label:'二次故障',value:'二次故障'},
			// 	{label:'异常信息',value:'异常信息'},],
			faultList: [

				// 可以根据需要添加更多数据
			],
			faultList_2: [

				// 可以根据需要添加更多数据
			],
			yc:[],
			ec:[],
			excepts:[],
			localType:'',
		}
	},
	methods: {
		// 在子组件的 methods 中添加
		resetSelection() {
			this.selectedID = []
			this.selectedID_2 = []
			this.selectedID_3 = []
			this.faultXiangWei = []
			this.faultFeature = ''
			this.distance = ''

			// 重置表格数据
			this.tableDataCopy = JSON.parse(JSON.stringify(this.tableData))
			this.tableDataCopy_2 = JSON.parse(JSON.stringify(this.tableData_2))
			this.tableDataCopy_3 = JSON.parse(JSON.stringify(this.tableData_3))

			// 通知父组件数据已清空
			this.$emit('updateData', {
				yc: [],
				ec: [],
				excepts: []
			})
		},
		saveName(val,index,ex_val){
			ex_val.forEach(item=>{
				if (item.val===val){
					this.selectedID_3[index].des=item.name
				}
			})
		},
		updateData(copy,data,faultXiangWei,faultFeature,distance) {
			const filteredData=data.filter(item => {
				const xiangwei = faultXiangWei.length === 0 || faultXiangWei.every(fault => item.name.includes(fault));
				const fault=faultFeature===''||item.name.includes(faultFeature)
				const number = distance === '' || item.name.includes(distance)
				return xiangwei&&fault&&number;
			});
			copy.splice(0, copy.length, ...filteredData);
		},
		selectRow(val,selectedID,type,index){
			if (type===1){
				if (!selectedID.includes(val)){
					selectedID.push(val)
				}else{
					selectedID.splice(selectedID.indexOf(val), 1);
				}
				this.yc=selectedID;
			}else if(type===2){
				if (!selectedID.includes(val)){
					selectedID.push(val)
				}else{
					selectedID.splice(selectedID.indexOf(val), 1);
				}
				this.ec=selectedID;
			}else if (type===3){
				if (!this.selectedID_3[index]) {
					this.$set(this.selectedID_3, index, { id: val, val: undefined });
				} else {
					this.$set(this.selectedID_3, index, null);
				}
				this.excepts = this.selectedID_3.filter(item => item !== null);

			}
			this.$emit('updateData',{yc:this.yc,ec:this.ec,excepts:this.excepts});
		},
		getDevInfo() {
			try {
				this.ws.send(
						JSON.stringify({
							cmd: 'getDeviceDataByStateDesc',
							deviceName: this.deviceName,
						})
				);
				this.ws.addEventListener('message', (e) => {
					const data = JSON.parse(e.data);
				if (data.cmd==="getDeviceDataByStateDesc"){
					this.jg_name=data.data.jg_name;
					this.data_id=data.data.data_id;
				}
				});
			} catch (error) {
				console.error('发送 WebSocket 消息时出错:', error);
			}
		},
		getTableData(){
			const params={"cmd":"getFaults","devName":this.deviceName}
			this.ws.send(JSON.stringify(params));
			console.log(params,'params')
			this.ws.addEventListener('message', (e) => {
				const data = JSON.parse(e.data);
				if (data.cmd==='getFaults'){
					console.log(data,'异常信息数据')
					this.tableData=data.data.yc;
					this.tableData_2=data.data.ec;
					this.tableData_3=data.data.gz_excep;
					this.tableData_3.forEach(item=>{
						item.ex_val=JSON.parse(item.ex_val)
					})
				}
				this.tableDataCopy=JSON.parse(JSON.stringify(this.tableData));
				this.tableDataCopy_2=JSON.parse(JSON.stringify(this.tableData_2));
				this.tableDataCopy_3=JSON.parse(JSON.stringify(this.tableData_3));

			});
		},
		async getJAList(){
			const res= await getJAn();
			if (res.data.code===200){
				this.jiaoAnList=res.data.data
			}else{
				this.$message.error('获取教案失败,请检查网络设置')
			}
		},

		async addEvent() {
			if (!this.selectedPlan) {
				this.$message.error('请选择教案');
				return;
			}
			const dataTemplate = {
				teachId: this.selectedPlan,
				intervalTime: this.timeInterval,
				devId: "",
				eventDesc: "",
				paramVal: "",
				contType:
						this.activeTab === "first"
								? "一次故障"
								: this.activeTab === "second"
										? "二次故障"
										: "异常",
				jgName: this.jg_name,
				devName: this.deviceName,
			};
			const processRequests = async (selectedIDs, tableData, customProcessor) => {
				const requests = selectedIDs
						.filter((item) => item !== null) // 过滤掉 null 值
						.map((item) => {
							const requestData = { ...dataTemplate }; // 每次复制模板
							customProcessor(requestData, item, tableData);

							// 处理 addJaEvent 的响应
							return addJaEvent(requestData)
									.then((response) => {
										// 检查后端返回的业务状态
										if (response.data.code !== 200) {
											this.$message.error(`后端业务错误：${response.data.msg}`);
											return { success: false, error: response.data.msg }; // 失败并返回错误信息
										}
										return { success: true }; // 请求成功且业务处理成功
									})
									.catch((error) => {
										this.$message.error(`请求失败：${error}`);
										return { success: false, error: error.message }; // 捕获 HTTP 请求错误
									});
						});

				// 等待所有请求完成
				const results = await Promise.allSettled(requests);

				// 统计成功和失败的数量
				const successCount = results.filter(
						(result) =>
								result.status === "fulfilled" &&
								result.value &&
								result.value.success
				).length;

				const failureCount = results.filter(
						(result) =>
								result.status === "rejected" || // 网络错误
								(result.status === "fulfilled" && result.value && !result.value.success) // 业务逻辑错误
				).length;

				// 显示结果
				if (failureCount > 0) {
					this.$message.error(
							`操作完成：成功 ${successCount} 条，失败 ${failureCount} 条`
					);
				} else {
					this.$message.success(`操作完成：成功 ${successCount} 条`);
				}
			};


			if (this.activeTab === "first") {
				if (this.selectedID.length===0){
					this.$message.error('请选择一次故障内容')
					return
				}
				// 一次故障处理逻辑
				await processRequests(
						this.selectedID.filter((item) => item !== null), // 过滤掉 null 的值
						this.tableData,
						(requestData, item, tableData) => {
							requestData.devId = item;
							const foundItem = tableData.find((items) => items.cl_index === item);
							if (foundItem) {
								requestData.eventDesc = foundItem.name;
							}
						}
				);

			} else if (this.activeTab === "second") {
				if (this.selectedID_2.length===0){
					this.$message.error('请选择二次故障内容')
					return
				}

				// 二次故障处理逻辑
				await processRequests(this.selectedID_2.filter((item) => item !== null), this.tableData_2, (requestData, item, tableData) => {
					requestData.devId = item;
					const foundItem = tableData.find((items) => items.cl_index === item);
					if (foundItem) {
						requestData.eventDesc = foundItem.name;
					}
				});
			} else {
				if (this.selectedID_3.length===0){
					this.$message.error('请选择异常内容')
					return
				}
				// 异常信息处理逻辑
				let canProceed = true;
				this.selectedID_3.forEach((item) => {
					if (item!==null&&item.id !== "" && item.val === undefined) {
						canProceed = false;
					}
				});
				if (!canProceed) {
					this.$message.error("有异常信息未选择状态");
					return;
				}

				await processRequests(
						this.selectedID_3.filter(
								(item) => item && item.id && item.val !== undefined // 过滤无效项
						),
						this.tableData_3,
						(requestData, item, tableData) => {
							const foundItem = tableData.find((items) => items.cl_index === item.id);
							requestData.devId = item.id;
							requestData.eventDesc = foundItem ? foundItem.name + item.des : item.des; // 安全处理
							requestData.paramVal = item.val;
						}
				);
			}
		}
	},
		props:{
		type:{
			type:String,
		},
		deviceName:{
			type:String,
		},
			index:{
				type:Number,
			}
	},
	watch:{
		index(newValue) {
			if (newValue){
				this.getJAList()
				this.getTableData();
				this.getDevInfo()
			}
		},
		type(newValue,oldValue){
			if (newValue!==oldValue){
			this.localType=newValue
			}else{
				this.localType=oldValue
			}
			this.activeTab=this.localType==='duanluqi'||this.localType==='shouche'||this.localType==='bileiqi'||this.localType==='dianyahuganqi'?'second':'first'
		},
	},
	computed:{
		showFirst(){
			const arr=['shouche','bileiqi','dianyahuganqi','duanluqi']
			return !arr.includes(this.type);
		}
	},
	mounted() {
		this.getJAList()
		 this.getTableData()
		 this.getDevInfo()
		console.log(this.type,'111111111111111111111')
		this.localType=this.type;
		this.activeTab=this.localType==='duanluqi'||this.localType==='shouche'||this.localType==='bileiqi'||this.localType==='dianyahuganqi'?'second':'first'
	}
}
</script>

<style scoped>
.fault-dialog-content {
	padding: 20px;
	color: #fff;
}

/* 覆盖 Element UI 的默认样式 */
:deep(.el-tabs__item) {
	color: rgba(255, 255, 255, 0.6);
}

:deep(.el-tabs__item.is-active) {
	color: #409EFF;
}

:deep(.el-tabs__nav-wrap::after) {
	background-color: rgba(255, 255, 255, 0.1);
}

:deep(.el-form-item__label) {
	color: rgba(255, 255, 255, 0.8);
}

:deep(.el-collapse-item__header) {
	background-color: transparent;
	color: rgba(255, 255, 255, 0.8);
	border-color: rgba(255, 255, 255, 0.1);
}

:deep(.el-collapse-item__content) {
	background-color: transparent;
	color: #fff;
	border-color: rgba(255, 255, 255, 0.1);
}

:deep(.el-checkbox__label) {
	color: rgba(255, 255, 255, 0.8);
}

:deep(.el-radio__label) {
	color: rgba(255, 255, 255, 0.8);
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
	background-color: transparent;
	color: rgba(255, 255, 255, 0.8);
	border-color: rgba(255, 255, 255, 0.2);
}

:deep(.el-input-number__decrease:hover),
:deep(.el-input-number__increase:hover) {
	color: #409EFF;
	background-color: rgba(64, 158, 255, 0.1);
}

:deep(.el-input__inner) {
	background-color: transparent;
	border-color: rgba(255, 255, 255, 0.2);
	color: #fff;
}

:deep(.el-input__inner:hover),
:deep(.el-input__inner:focus) {
	border-color: #409EFF;
}

:deep(.el-select-dropdown__item) {
	color: rgba(255, 255, 255, 0.8);
}

:deep(.el-select-dropdown__item.hover) {
	background-color: rgba(64, 158, 255, 0.1);
}

:deep(.el-select-dropdown__item.selected) {
	color: #409EFF;
	background-color: rgba(64, 158, 255, 0.1);
}

:deep(.el-slider__runway) {
	background-color: rgba(255, 255, 255, 0.2);
}

:deep(.el-slider__bar) {
	background-color: #409EFF;
}

:deep(.el-slider__button) {
	border-color: #409EFF;
	background-color: #409EFF;
}

:deep(.el-collapse) {
	border-color: rgba(255, 255, 255, 0.1);
	background-color: transparent;
}

.distance-slider {
	width: 300px;
}

.ms-label {
	margin-left: 5px;
	color: rgba(255, 255, 255, 0.8);
}

.el-collapse {
	margin: 10px 0;
	border-color: rgba(255, 255, 255, 0.1);
}

/* 修复下拉菜单的背景色 */
:deep(.el-select-dropdown) {
	background-color: rgb(2, 22, 42);
	border-color: rgba(255, 255, 255, 0.1);
}

/* 修复弹出层的背景色 */
:deep(.el-popper[x-placement^="bottom"]) {
	background-color: rgb(2, 22, 42);
}

/* 修改折叠面板的样式 */
:deep(.el-collapse) {
	border: none;
	background-color: transparent;
}

:deep(.el-collapse-item) {
	margin-bottom: 1px;
}

:deep(.el-collapse-item__header) {
	background-color: rgba(255, 255, 255, 0.05);
	color: rgba(255, 255, 255, 0.8);
	border: none;
	padding: 0 15px;
	height: 40px;
	line-height: 40px;
}

:deep(.el-collapse-item__header:hover) {
	background-color: rgba(255, 255, 255, 0.1);
}

:deep(.el-collapse-item__content) {
	background-color: rgba(255, 255, 255, 0.02);
	color: rgba(255, 255, 255, 0.8);
	border: none;
	padding: 15px;
}

:deep(.el-collapse-item__arrow) {
	color: rgba(255, 255, 255, 0.8);
}

:deep(.el-collapse-item__header.is-active) {
	border-bottom-color: transparent;
}

:deep(.el-collapse-item__wrap) {
	border: none;
	background-color: transparent;
}

/* 添加新的样式 */
.fault-list {
	margin-top: 20px;
}

:deep(.el-table) {
	background-color: transparent;
	color: rgba(255, 255, 255, 0.8);
	border: 1px solid rgb(28, 46, 64);
}

:deep(.el-table::before) {
	display: none;
}

:deep(.el-table td),
:deep(.el-table th.is-leaf) {
	border-bottom: 1px solid rgb(28, 46, 64);
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
	border-right: 1px solid rgb(28, 46, 64);
}

:deep(.el-table thead) {
	border-bottom: 1px solid rgb(28, 46, 64);
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
	background-color: rgba(2, 22, 42) !important;
}

.cancel-fault-buttons {
	display: flex;
	gap: 10px;
}

:deep(.el-textarea__inner) {
	background-color: transparent;
	border-color: rgba(255, 255, 255, 0.2);
	color: #fff;
}

:deep(.el-textarea__inner:focus) {
	border-color: #409EFF;
}

:deep(.el-table__empty-block) {
	background-color: transparent;
}

:deep(.el-table__empty-text) {
	color: rgba(255, 255, 255, 0.6);
}
.txts{
	width: 99%;
	border: 1px solid #ccc;
	height: 15rem;
	overflow: auto;
}
.table-row {
	display: flex;
	cursor: pointer;
	transition: background-color 0.3s;
}

.table-row:hover {
	background-color: rgb(4, 32, 62); /* 鼠标悬浮时的颜色 */
}

.table-row.selected {
	background-color:rgb(6, 42, 82); /* 选中时的颜色 */
}

.el-button {
	color: #ebeff0;
	background: linear-gradient(#176575, #07283f);
	border: 0;
	box-shadow: 0 -2px 0 rgba(16, 164, 195, 0.8);
	cursor: pointer;
	transition: all 0.3s ease;

	&:hover {
		background: linear-gradient(#1a7384, #083850);
		box-shadow: 0 -2px 0 rgba(16, 164, 195, 1);
	}

	&:active {
		background: linear-gradient(#145c66, #06283a);
		box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.3);
		transform: translateY(1px);
	}
}
</style>
